package com.yh.frame;

import info.clearthought.layout.TableLayout;
import info.clearthought.layout.TableLayoutConstraints;

import java.awt.AWTException;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * @author zhangpinga
 */
public class JandanWeb extends JFrame {
	static JandanWeb jandanWeb = null;
	
	public static void main ( String [ ] args ) {
		jandanWeb = new JandanWeb ( );
		jandanWeb.setTitle ( "煎蛋服务器" );
		// jandanWeb.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
		jandanWeb.setVisible ( true );
		jandanWeb.initImage ( );
		jandanWeb.startServer ( );
		
		jandanWeb.addWindowListener ( new WindowAdapter ( ) {
			public void windowClosing ( WindowEvent e ) {
				if ( !SystemTray.isSupported ( ) ) System.exit ( 0 );
				jandanWeb.setVisible ( false );
				jandanWeb.showTrayIcon ( );
			}
		} );
	}
	
	// /////////////////////////////////////////////////
	static Image image = null;
	
	private void initImage ( ) {
		for ( String img : tray_icon_list ) {
			if ( new File ( img ).exists ( ) ) {
				image = Toolkit.getDefaultToolkit ( ).getImage ( img );
				System.out.println ( "tray_icon=[" + img + "]" );
				break;
			}
		}
		if ( null == image ) image = Toolkit.getDefaultToolkit ( ).getImage ( "jandan.bmp" );
		jandanWeb.setIconImage ( image );
	}
	
	// /////////////////////////////////////////////////
	
	TrayIcon trayIcon = null;
	
	private void showTrayIcon ( ) {
		PopupMenu popup = new PopupMenu ( );
		MenuItem seePicItem = new MenuItem ( "看图 .." );
		MenuItem updateconfigItem = new MenuItem ( "更新配置" );
		MenuItem openItem = new MenuItem ( "打开[" + getTitle ( ) + "]" );
		MenuItem exitItem = new MenuItem ( "退出 .. " );
		seePicItem.addActionListener ( new ActionListener ( ) {
			public void actionPerformed ( ActionEvent e ) {
				// if ( null != trayIcon ) SystemTray.getSystemTray ( ).remove ( trayIcon );
				openIE ( );
			}
		} );
		updateconfigItem.addActionListener ( new ActionListener ( ) {
			public void actionPerformed ( ActionEvent e ) {
				// if ( null != trayIcon ) SystemTray.getSystemTray ( ).remove ( trayIcon );
				updateConfig ( );
			}
		} );
		openItem.addActionListener ( new ActionListener ( ) {
			public void actionPerformed ( ActionEvent e ) {
				if ( null != trayIcon ) SystemTray.getSystemTray ( ).remove ( trayIcon );
				setVisible ( true );
				trayIcon = null;
			}
		} );
		exitItem.addActionListener ( new ActionListener ( ) {
			public void actionPerformed ( ActionEvent e ) {
				System.exit ( 0 );
			}
		} );
		popup.add ( seePicItem );
		popup.add ( updateconfigItem );
		popup.add ( openItem );
		popup.add ( exitItem );
		
		// trayIcon = new TrayIcon ( image , "jandan 服务器["+imgname+"]" , popup );// 创建trayIcon
		trayIcon = new TrayIcon ( image , getTitle ( ) , popup );// 创建trayIcon
		trayIcon.addActionListener ( new ActionListener ( ) {
			public void actionPerformed ( ActionEvent e ) {
				if ( null != trayIcon ) SystemTray.getSystemTray ( ).remove ( trayIcon );
				setVisible ( true );
				trayIcon = null;
			}
		} );
		
		try {
			SystemTray.getSystemTray ( ).add ( trayIcon );
		} catch ( AWTException e1 ) {
		}
	}
	
	protected void updateConfig ( ) {
		try {
			String url = "http://127.0.0.1:" + App.getPort ( ) + "/config/updateConfig";
			HttpResponse resp = new DefaultHttpClient ( ).execute ( new HttpPost ( url ) );
			String result = EntityUtils.toString ( resp.getEntity ( ) , "UTF-8" );
			if ( "0".equals ( result ) ) JOptionPane.showMessageDialog ( this , "更新成功" );
			else JOptionPane.showMessageDialog ( this , "更新失败,请联系管理员" );
			resp = null;
		} catch ( IOException e ) {
			JOptionPane.showMessageDialog ( this , "更新失败,请联系管理员[" + e.getLocalizedMessage ( ) + "]" );
		}
	}
	
	// /////////////////////////////////////////////////
	private static String _info_text = "";
	
	private void setInfo ( final String info ) {
		_info_text = info;
	}
	
	private void start_info_thread ( ) {
		new Thread ( new Runnable ( ) {
			private String _old_text = "_old_text";
			
			public void run ( ) {
				while ( true ) {
					for ( int i = 0 ; i < 10 ; i++ ) {
						if ( !_old_text.equals ( _info_text ) ) {
							i = 0;
							_old_text = _info_text;
						}
						info.setText ( _info_text );
						try {
							Thread.sleep ( 500L );
						} catch ( Exception e ) {
							e.printStackTrace ( );
						}
					}
					_info_text = "";
				}
			}
		} ).start ( );
		
	}
	
	// /////////////////////////////////////////////////
	
	private void startServer ( ) {
		new Thread ( new Runnable ( ) {
			public void run ( ) {
				int i = 0;
				try {
					setInfo ( "启动中..." );
					btnStart.setEnabled ( false );
					if ( !App.isRunning ( ) ) new App ( ).run ( );
					while ( true ) {
						Thread.sleep ( 500L );
						if ( App.isRunning ( ) || i++ > 20 ) break;
					}
					if ( App.isRunning ( ) ) setInfo ( "服务器已经启动在" + App.getPort ( ) + "端口" );
					else setInfo ( "启动失败,检查端口" );
					
				} catch ( Exception e ) {
					e.printStackTrace ( );
				} finally {
					btnStart.setEnabled ( true );
				}
			}
		} ).start ( );
	}
	
	class JandanServer implements ActionListener {
		public void actionPerformed ( ActionEvent e ) {
			if ( App.isRunning ( ) ) {
				setInfo ( "服务器已经启动啦" );
				return;
			}
			startServer ( );
		}
		
	}
	
	class JandanIE implements ActionListener {
		public void actionPerformed ( ActionEvent e ) {
			if ( !App.isRunning ( ) ) {
				JOptionPane.showMessageDialog ( null , "先启动服务器" );
				setInfo ( "先启动服务器" );
				return;
			}
			openIE ( );
		}
		
	}
	
	private void openIE ( ) {
		String url = "http://127.0.0.1:" + App.getPort ( ) + "/";
		try {
			// 创建一个URI实例
			java.net.URI uri = java.net.URI.create ( url );
			// 获取当前系统桌面扩展
			java.awt.Desktop dp = java.awt.Desktop.getDesktop ( );
			// 判断系统桌面是否支持要执行的功能
			if ( dp.isSupported ( java.awt.Desktop.Action.BROWSE ) ) {
				// 获取系统默认浏览器打开链接
				dp.browse ( uri );
			} else {
				JOptionPane.showMessageDialog ( null , "请手工打开网址:" + url );
			}
			
		} catch ( Exception e ) {
			e.printStackTrace ( );
			JOptionPane.showMessageDialog ( null , "请手工打开网址:" + url );
		}
	}
	
	public JandanWeb ( ) {
		initComponents ( );
		start_info_thread ( );
	}
	
	static List < String > tray_icon_list = new ArrayList < String > ( );
	static {
		String path = System.getProperty ( "user.dir" );
		tray_icon_list.add ( path + File.separator + "res/jandan.gif" );
		tray_icon_list.add ( path + File.separator + "res/jandan.png" );
		tray_icon_list.add ( path + File.separator + "res/jandan.jpg" );
		tray_icon_list.add ( path + File.separator + "res/jandan.ico" );
		tray_icon_list.add ( path + File.separator + "jandan.gif" );
		tray_icon_list.add ( path + File.separator + "jandan.png" );
		tray_icon_list.add ( path + File.separator + "jandan.jpg" );
	}
	
	private void initComponents ( ) {
		// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
		label1 = new JLabel ( );
		label2 = new JLabel ( );
		btnStart = new JButton ( );
		btnIE = new JButton ( );
		label3 = new JLabel ( );
		// label5 = new JLabel ( );
		info = new JLabel ( );
		// autocatch = new JCheckBox();
		
		// ======== this ========
		setMinimumSize ( new Dimension ( 300 , 150 ) );
		Container contentPane = getContentPane ( );
		contentPane.setLayout ( new TableLayout ( new double [ ] [ ] { { TableLayout.MINIMUM , TableLayout.FILL , TableLayout.FILL , TableLayout.PREFERRED , TableLayout.MINIMUM } ,
				{ TableLayout.PREFERRED , TableLayout.PREFERRED , TableLayout.PREFERRED , TableLayout.PREFERRED , TableLayout.PREFERRED } } ) );
		( (TableLayout) contentPane.getLayout ( ) ).setHGap ( 5 );
		( (TableLayout) contentPane.getLayout ( ) ).setVGap ( 5 );
		
		// ---- label1 ----
		label1.setText ( "  " );
		contentPane.add ( label1 , new TableLayoutConstraints ( 1 , 1 , 1 , 1 , TableLayoutConstraints.FULL , TableLayoutConstraints.FULL ) );
		
		// ---- label2 ----
		label2.setText ( "  " );
		contentPane.add ( label2 , new TableLayoutConstraints ( 0 , 2 , 0 , 2 , TableLayoutConstraints.FULL , TableLayoutConstraints.FULL ) );
		
		// ---- btnStart ----
		btnStart.setText ( "\u542f\u52a8\u670d\u52a1\u5668" );
		btnStart.addActionListener ( new JandanServer ( ) );
		contentPane.add ( btnStart , new TableLayoutConstraints ( 1 , 2 , 1 , 2 , TableLayoutConstraints.FULL , TableLayoutConstraints.FULL ) );
		
		// ---- btnIE ----
		btnIE.setText ( "\u770b\u56fe" );
		btnIE.addActionListener ( new JandanIE ( ) );
		contentPane.add ( btnIE , new TableLayoutConstraints ( 2 , 2 , 2 , 2 , TableLayoutConstraints.FULL , TableLayoutConstraints.FULL ) );
		
		// ---- label3 ----
		label3.setText ( " " );
		contentPane.add ( label3 , new TableLayoutConstraints ( 4 , 2 , 4 , 2 , TableLayoutConstraints.FULL , TableLayoutConstraints.FULL ) );
		
		// ---- label5 ----
		contentPane.add ( new JLabel ( " " ) , new TableLayoutConstraints ( 1 , 3 , 1 , 3 , TableLayoutConstraints.FULL , TableLayoutConstraints.FULL ) );
		
		// ---- info ----
		info.setText ( " " );
		contentPane.add ( info , new TableLayoutConstraints ( 1 , 4 , 2 , 4 , TableLayoutConstraints.FULL , TableLayoutConstraints.FULL ) );
		pack ( );
		setLocationRelativeTo ( getOwner ( ) );
		// JFormDesigner - End of component initialization //GEN-END:initComponents
	}
	
	// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
	private JLabel label1;
	private JLabel label2;
	private JButton btnStart;
	private JButton btnIE;
	private JLabel label3;
	// private JLabel label5;
	private JLabel info;
	// JFormDesigner - End of variables declaration //GEN-END:variables
	
	private static final long serialVersionUID = -8498636383647803645L;
}
